//
//  Obj.cpp
//  NinjaTurtle
//
//  Created by Nguyen Tri Chung on 1/27/15.
//
//

#include "Obj.h"

Obj::Obj() {
    this->autorelease();
    this->sprites = new Vector<CSprite*>();
    this->body = NULL;
}

Obj::~Obj() {
    CC_SAFE_DELETE(this->sprites);
    CC_SAFE_RELEASE(this->body);
}

void Obj::update(float dt) {
    if (this->sprites != NULL) {
        for (auto iter = this->sprites->begin(); iter != this->sprites->end(); iter++) {
            CSprite* cSprite = (CSprite*) *iter;
            if (cSprite != NULL) {
                if (this->body != NULL) {
                    if (strcmp(cSprite->getSpriteType().data(), SPRITE_TYPE_MAIN) == 0) {
                        cSprite->setVisible(this->body->getVisible());
                    }
                    cSprite->setPosition(this->body->getPosition() + cSprite->getOOVector());
                    cSprite->setAnchorPoint(this->body->getAnchorPoint());
                    cSprite->setRotation(-this->body->getRotation());
                    cSprite->setScale(this->body->getScale());
                    cSprite->setFlippedX(this->body->getFlipX());
                }
            }
        }
    }
    
    if (this->body != NULL) {
        this->body->update(dt);
    }
}

void Obj::setPosition(Point position) {
    this->body->setPosition(position);
}

Point Obj::getPosition() {
    return this->body->getPosition();
}

CSprite* Obj::getSprite(const string& spriteType) {
    for (auto iter = this->sprites->begin(); iter != this->sprites->end(); iter++) {
        CSprite* cSprite = (CSprite*) *iter;
        if (cSprite != NULL) {
            if (cSprite->getSpriteType() == spriteType) {
                return cSprite;
            }
        }
    }
    return NULL;
}

void Obj::removeSprite(const string& spriteType) {
    for (auto iter = this->sprites->begin(); iter != this->sprites->end(); iter++) {
        CSprite* cSprite = (CSprite*) *iter;
        if (cSprite != NULL) {
            if (cSprite->getSpriteType() == spriteType) {
                this->sprites->eraseObject(cSprite);
                break;
            }
        }
    }
}

RectBody* Obj::getRectBody() {
    return (RectBody*) this->body;
}

void Obj::play(const string& spriteType, const string& action) {
    CSprite* cSprite = this->getSprite(spriteType);
    cSprite->play(action);
}

void Obj::playLoop(const string& spriteType, const string& action) {
    CSprite* cSprite = this->getSprite(spriteType);
    cSprite->playLoop(action);
}
